#pragma once

#include <iostream>
#include <vector>
#include <string>
#include <memory>
#include <unordered_map>
#include <functional>
#include <cstring>
#include <cerrno>
#include <cstdlib>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "err.hpp"
#include "loop_queue.hpp"

namespace udp
{
const uint16_t default_port = 8080;

class udp_server
{
using func_t = std::function<std::string(std::string)>;

public:
    udp_server(func_t cb, uint16_t port = default_port, std::string ip = "any")
        : _port(port), _ip(ip)
    {
        _services.push_back(cb);
    }

    ~udp_server()
    {
        _pdr.join();
        _csr.join();
    }

    void init()
    {
        _sock = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sock < 0)
        {
            std::cerr << "socket error " << strerror(errno) << std::endl;
            exit(SOCKET_ERR);
        }
        std::cout << "create socket success " << _sock << std::endl;

        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        // local.sin_addr.s_addr = inet_addr(_ip.c_str());
        local.sin_addr.s_addr = INADDR_ANY;

        if (bind(_sock, (struct sockaddr*)&local, sizeof(local)) < 0)
        {
            std::cerr << "bind error " << strerror(errno) << std::endl;
            exit(BIND_ERR);
        }
        std::cout << "bind success" << std::endl;

        _pdr = std::thread(&udp_server::start, this);
        _csr = std::thread(&udp_server::board_cast, this);
    }

    void add_user(const std::string& name, struct sockaddr_in& addr)
    {
        std::unique_lock<std::mutex> lock(_mtx);

        if (users.find(name) == users.end())
            users.insert({name, addr});
    }

    void start()
    {
        char buf[128] = {0};
        while (true)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer); // peer struct buffer's size

            ssize_t s = recvfrom(_sock, buf, sizeof(buf) - 1, 0, (struct sockaddr*)&peer, &len);
            if (s > 0) buf[s] = 0;
            else continue;

            std::string peer_ip = inet_ntoa(peer.sin_addr);
            uint16_t peer_port = ntohs(peer.sin_port);
            // std::cout << "[" << peer_ip << ":" <<  peer_port << "]# " << buf << std::endl;
            
            std::string name = peer_ip + ":" + std::to_string(peer_port);
            add_user(name, peer);

            _queue.push(std::string(buf));
        }
    }

    void board_cast()
    {
        while (true)
        {
            std::string msg;
            _queue.pop(&msg);

            for (auto& user : users)
            {
                std::cout << "cast message to user " << user.first << std::endl;
                std::string rsp = '[' + user.first + "] " + msg;
                sendto(_sock, rsp.c_str(), rsp.size(), 0, (struct sockaddr*)&user.second, sizeof(user.second));
            }
        }
    }

private:
    int _sock;
    int _port;
    std::string _ip;
    std::vector<func_t> _services;
    std::unordered_map<std::string, struct sockaddr_in> users;
    loop_queue<std::string> _queue;
    std::mutex _mtx;

    std::thread _pdr;
    std::thread _csr;
};

}
